package emulator.assembler;

import java.util.SortedMap;
import java.util.TreeMap;
import java.util.Map.Entry;

import emulator.hardware.HwWord;

public class InstructionList {
	private SymbolTable symbols;
	private SortedMap<Integer, Instruction> instructions;

	public InstructionList(SymbolTable symbols)
	{
		this.symbols = symbols;
		this.instructions = new TreeMap<Integer, Instruction>();
	}
	
	public void addInstruction(int address, Instruction instruction)
	{
		instructions.put(address, instruction);
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		String listing = "";
		for (Entry<Integer,Instruction> entry : instructions.entrySet())
		{
			listing += new HwWord(entry.getKey()).toString() + "  ";
			String raw_bytes = entry.getValue().getBytes() + "            ";
			listing += raw_bytes.substring(0, 12);
			String label = symbols.getJumpLabel(entry.getKey());
			if (label != null)
			{
				if (label.length() > 10)
					label = label.substring(0,10);
				label += ":";
			}
			else
				label = "";
			label += "                          ";
			listing += label.substring(0, 12);
			String opcode = entry.getValue().getOpcode() + "      ";
			listing += opcode.substring(0, 5);
			String operand = entry.getValue().getOperand() + "               ";
			listing += operand.substring(0, 12);
			String remark = symbols.getRemark(entry.getKey());
			if (remark != null)
				listing += " ; "+remark;
			listing += "\n";
		}
		return listing;
	}

	public int getByteCount() {
		int byte_count = 0;
		for (Entry<Integer,Instruction> entry : instructions.entrySet())
		{
			byte_count += entry.getValue().getByteCount();
		}
		return byte_count;
	}

	public int getCount() {
		return instructions.size();
	}

	public int getAddress(int index) {
		return (Integer) instructions.keySet().toArray()[index];
	}

	public Instruction getInstruction(int index) {
		return (Instruction) instructions.values().toArray()[index];
	}
}
